"""
Course auth views.
"""
MY_PATH = 'betterspace.courses.auth'
import urllib

from django.shortcuts import render_to_response, redirect
from django.http import HttpResponseRedirect
from courses.auth.decorators import required_role

LOGIN_PAGE_URL='/user/login/'
def login_page(request, redirect_to=None):
    #after logging in, where do we go?
    redirect_to = request.GET.get('redirect_to', PROFILE_HOME_URL)
    
    context = request.GET.get('context', None)
    
    if context == 'failed':
        print 'failed login...'
        template = 'user/login/failed.tpl'
    elif context == 'logout':
        print 'just logged out...'
        template = 'user/login/logout.tpl'
    elif context == 'redirect':
        print 'redirected here...'
        template = 'user/login/redirect.tpl'
    else:
        template = 'user/login/base.tpl'
    
    return render_to_response(template, {'redirect_url': urllib.unquote(redirect_to)})

DO_LOGIN_URL='/user/do_login/'
def do_login(request):
    from django.contrib.auth import authenticate, login
    
    redirect_to = request.POST.get('redirect_to', '/user/home/')
    
    username = request.POST['username']
    password = request.POST['password']
    
    user = authenticate(username=username,password=password)
    
    if user is not None and user.is_active:
        login(request, user)
        return redirect(redirect_to)
    else:
        return redirect(LOGIN_PAGE_URL+'?context=failed')

DO_LOGOUT_URL='/user/logout'
def do_logout(request):
    from django.contrib.auth import logout
    logout(request)
    return redirect(LOGIN_PAGE_URL + '?context=logout')


PROFILE_HOME_URL='/user/home/'

def profile_home(request):
    if request.user.is_anonymous():
        if request.get_full_path() == PROFILE_HOME_URL:
            return redirect(LOGIN_PAGE_URL)
        return redirect(
            LOGIN_PAGE_URL+'?context=redirect&redirect_to=%s' % 
            urllib.urlencode(request.get_full_path())
        )
        
    
    return render_to_response('user/home.tpl',
        {
            'profile': request.profile
        }
    )
